package com.zhsource.user.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhsource.system.domain.Logininfo;
import com.zhsource.system.mapper.LogininfoMapper;
import com.zhsource.user.domain.User;
import com.zhsource.user.mapper.UserMapper;
import com.zhsource.user.query.UserQuery;
import com.zhsource.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;


    @Override
    public List<User> list() {
        return userMapper.list();
    }

    @Override
    public User selectById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public PageInfo<User> page(UserQuery userQuery) {
        // 2.分页查询数据
        PageHelper.startPage(userQuery.getCurrentPage(), userQuery.getPageSize());
        List<User> page = userMapper.page(userQuery);
        PageInfo<User> userPageInfo = new PageInfo<>(page);
        return userPageInfo;
    }

    @Override
    public void insert(User user) {
        userMapper.insert(user);

        // 新建一个logininfo信息对象
        Logininfo logininfo = new Logininfo();
        logininfo.setUsername(user.getRealName());
        logininfo.setEmail(user.getEmail());
        logininfo.setPhone(user.getPhone());
        logininfo.setPassword("$2a$10$/7mXZXC/avBJ/ScPlGlXxe6bhX4b7XRB9.UQSk4kt6ePw.2YMIHoq");
        logininfo.setSalt("RaVhRTiPfy2i1uZq7rMHEXsZYAWzu3VA");
        logininfo.setType(1);
        logininfo.setDisable(true);
        // 插入或新增logininfo信息
        logininfoMapper.insertOrUpdateLoginInfo(logininfo);
        //设置用户的登录信息Id
        user.setLogininfoId(logininfo.getId());

        //更新用户信息
        userMapper.update(user);
    }

    @Override
    public void update(User user) {
        userMapper.update(user);

        // 得到旧的用户ID信息
        User user1 = userMapper.selectById(user.getId());

        // 同步维护logininfo表
        // 创建一个新的logininfo信息对象
        Logininfo logininfo = new Logininfo();
        logininfo.setId(user1.getLogininfoId());
        logininfo.setUsername(user.getRealName());
        logininfo.setEmail(user.getEmail());
        logininfo.setPhone(user.getPhone());

        // 更新登录信息
        logininfoMapper.updateLoginInfo(logininfo);
        // 更新员工信息
//        userMapper.updateLoginInfo(user);

    }

    @Override
    public void delete(Long id) {
        User user = userMapper.selectById(id);
        Long logininfoId = user.getLogininfoId();
        userMapper.delete(id);
        //删除logininfo表中对应信息
        logininfoMapper.deleteLoginInfo(logininfoId);

    }

    @Override
    public void batchDel(List<Long> ids) {
        userMapper.batchDelLogininfo(ids);
//        userMapper.batchDel(ids);
    }
}
